const placeModel = require('../models/places.model')
const logger = require('../utils/logger')

class PlaceService {
  places = placeModel
  async findAll ({ page = 1, pageSize = 100, area, name, owner, status }) {
    const query = {
      deleted: false,
    }
    if (name) {
      query.name = { $regex: new RegExp(name, 'i') }
    }
    if (area) {
      query.area = area
    }
    if (owner) {
      query.owner = owner
    }
    if (status) {
      query.status = status
    }
    const sort = {
      createdDate: -1
    }
    page = parseInt(page) || 1
    const limit = parseInt(pageSize) || 100
    const skip = (page - 1) * (limit)
    const data = await this.places.find(query).sort(sort).skip(skip).limit(limit).populate('owner').populate('registration')
    const totalSize = await this.places.countDocuments(query)
    return {
      data,
      totalSize
    }
  }
  findOne (id) {
    return this.places.find({ deleted: false, _id: id }).populate('owner').populate('registration')
  }
  updateOne (id, data) {
    return this.places.findOneAndUpdate({ _id: id }, data)
  }
  deleteOne (id) {
    return this.places.findOneAndUpdate({ _id: id }, { deleted: true })
  }
  async addOne (doc) {
    // TODO check doc
    logger.info('place created ', doc)
    return await this.places.create(doc)
  }
}

module.exports = PlaceService